<?php

namespace App\Policies;

use App\Models\Project;
use App\Models\User;
use Helper;
use Illuminate\Auth\Access\HandlesAuthorization;

class ProjectPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * 列表
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function index(User $_user, Project $_project)
    {
        return Helper::isActions($_user, 'project');
    }

    /**
     * 新增
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function create(User $_user, Project $_project)
    {
        return Helper::isActions($_user, 'project.create');
    }

    /**
     * 插入
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function store(User $_user, Project $_project)
    {
        return Helper::isActions($_user, 'project.store');
    }

    /**
     * 详情
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function show(User $_user, Project $_project)
    {
        return $this->isActions($_user, 'project.show');
    }

    /**
     * 编辑
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function edit(User $_user, Project $_project)
    {
        return $this->isActions($_user, 'project.edit');
    }

    /**
     * 修改
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function update(User $_user, Project $_project)
    {
        return $this->isActions($_user, 'project.update');
    }

    /**
     * 删除
     * @param User $_user
     * @param Project $_project
     * @return bool
     */
    public function destroy(User $_user, Project $_project)
    {
        return $this->isActions($_user, 'project.destroy');
    }

    /**
     * 验证是否有权限
     * @param $_user
     * @param $action_key
     * @return bool
     */
    private function isActions($_user, $action_key){
        $action_keys = $_user->role->actions;
        if (is_array($action_keys)) {
            if ($action_keys === []) {
                return true;
            } else {
                $actions = Action::whereIn('key', [$action_key])->count();
                return $actions;
            }
        } else {
            return false;
        }
    }

}
